package com.ljkj.blockpay.network.interceptor;

import android.text.TextUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @Author: hongchen
 * @Email: chenhong289@jd.com
 * @Date: 2019-11-19 10:41
 * @Version: V1.0
 * @Description: 重试拦截器
 */
public class RetryInterceptor implements Interceptor {

    public static final int MAX_RETRY_NUM = 5;

    private int retryNum = 0;//假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）

    public RetryInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String retry = request.header("retry_max_num");
        if (TextUtils.isEmpty(retry)) {
            return chain.proceed(request);
        }
        int maxRetry = 0;
        try {
            maxRetry = Integer.parseInt(retry);
        } catch (Exception ignore) {
        }
        maxRetry = Math.min(maxRetry, MAX_RETRY_NUM);
        if (maxRetry <= 0) {
            return chain.proceed(request);
        }

        Response response = chain.proceed(request);
        while (!response.isSuccessful() && retryNum < maxRetry) {
            retryNum++;
            response = chain.proceed(request);
        }
        return response;
    }
}
